﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp12
{
    class Program
    {
        static Semaphore semaphore;
        //当前信号量中线程数量
        static int count;
        //用于生成随机数
        static Random r;

        static void Main()
        {
            r = new Random();
            //初始化信号量：初始请求数为1，最大请求数为3
            semaphore = new Semaphore(1, 3);
            //放出10个线程
            for (int i = 0; i < 5; i++)
            {
                int id = i + 1;
                Task.Run(() => {
                   
                    PrintStatus(id, "等待");
                    semaphore.WaitOne();
                    PrintStatus(id, "进入");
                    PrintCount(1);
                    Thread.Sleep(r.Next(1000));
                    PrintStatus(id, "退出");
                    PrintCount(-1);
                    semaphore.Release();
                });
            }
               
               // ThreadPool.QueueUserWorkItem(doo, i + 1);
            Console.ReadKey(true);
        }

        static void doo(object arg)
        {
            int id = (int)arg;
            PrintStatus(id, "等待");
            Console.WriteLine();
            semaphore.WaitOne();
            PrintStatus(id, "进入");
            PrintCount(1);
            Thread.Sleep(r.Next(1000));
            PrintStatus(id, "退出");
            PrintCount(-1);
            semaphore.Release();

        }

        //输出线程状态
        static void PrintStatus(int id, string s)
        {
            Console.WriteLine("线程{0}：{1}", id, s);
        }

        //修改并输出线程数量
        static void PrintCount(int add)
        {
            Interlocked.Add(ref count, add);
            Console.WriteLine("=> 信号量值：{0}", Interlocked.Exchange(ref count, count));
        }
    }
}
